<?
require_once($_SERVER["DOCUMENT_ROOT"] . '/db/db.php');
$file = 'query.csv';
$where = "";
// Opens a connection to a db server.
$list = Array('city' => 'blue', 'zip' => 'purple', 'price' => 'green');
$db = new DBConnection('dbname=assclap_realty port=5432 user=assclap_assclap password=fibo1235');
if (isset($_GET['BY']))
{
	$what = $_GET['BY'];
	$whereandorder = "WHERE $what = '$_GET[$what]' AND property_aux.rating = 1 ORDER BY $what";
	$file = preg_replace("/[^a-z\d]/i", "", $_GET[$what]) . '.csv';
}

$sql = "SELECT property.*, property_aux.rating, property_aux.comments, x(the_geom) as lon, y(the_geom) as lat FROM property inner join property_aux on (property_aux.mls_id = property.mls_id) $whereandorder ";
$Query = $db->CreateQuery($sql);

// Creates the Document.
$csv = array('Address, City, State, Zip, Name, Longitude, Latitude');

// Iterates through the results, creating one Placemark for each row.
while ($row = $Query->FetchRow())
{
	// Creates a Placemark and append it to the Document.
	$csv[] = '"' . $row['address'] . '", ' 
	. '"' . $row['city'] . '", '
	. '"' . $row['state'] . '", '
	. '"' . $row['zip'] . '", '
	. '"' . $row['price'] . '", '
	. $row['lon'] . ', '
	. $row['lat'];
}

$csvOutput = join("\n", $csv);
header('Content-type: application/csv');
header('Content-disposition: attachment; filename='. $file);
echo $csvOutput;
?>

